#include <string>
#include <string.h>
#include <stdlib.h>
#include "msgList.h"

using namespace lst;

MsgList::MsgList(int isTitle)
{
    if (isTitle == 1)
    {
        _isTitle = isTitle;
    }
}

void MsgList::_show_title()
{
    for (int i = 0; i < _row_width; i++)
    {
        cout << '*';
    }
    cout << endl;
}

void MsgList::_show_cmd()
{
    cout<<"(quit to exit,help to help)"<<endl;
    cout << "input msg to send(q exit h help):";
}

void MsgList::_show_hello()
{
    system("cls");
    if (_isTitle)
    {
        _show_title();
    }

    for (int i = 0; i < _list_height; i++)
    {
        cout << _list_screen[i] << endl;
    }

    _show_cmd();
}

char **MsgList::_str_to_list_data_rows(const char *str)
{
    int len = strlen(str);
    int data_row = len / _row_width;
    int data_over = len % _row_width;
    if (data_over)
    {
        data_row++;
    }
    _data_rows = data_row;
    char **data = new char *[data_row];
    char *row;
    for (int i = 0; i < len; i++)
    {
        if (i % _row_width == 0)
        {
            row = new char[_row_width];
            data[i / _row_width] = row;
        }
        row[i % _row_width] = str[i];
    }

    return data;
}

void MsgList::_list_up_play()
{
    int len = _list_height - 1;
    for (int i = 0; i < len; i++)
    {
        for (int j = 0; j < _row_width; j++)
        {
            _list_screen[i][j] = _list_screen[i + 1][j];
        }
    }
}

void MsgList::_push_rows(const char **str)
{
    for (int i = 0; i < _data_rows; i++)
    {
        if (_current_row >= _list_height)
        {
            _list_up_play();
            _current_row = _list_height - 1;
        }
        //_clear_row(_current_row);
        for (int j = 0; j < _row_width; j++)
        {
            _list_screen[_current_row][j] = str[i][j];
        }
        _list_screen[_current_row][_row_width] = '\0';

        if(i == (_data_rows-1)){
            int last = strlen(str[i])-1;
            _list_screen[_current_row][last] = '\0';       
        }

        delete[] str[i];
        _current_row++;
    }
}

void MsgList::_clear_row(int row)
{
    for (int i = 0; i < _row_width; i++)
    {
        _list_screen[row][i] = '0';
    }
}

/*******************************PUBLIC************************************/

void MsgList::push(const char *str)
{
    _push_rows((const char **)(_str_to_list_data_rows(str)));
}

void MsgList::print_list()
{
    _show_hello();
}

void MsgList::test()
{
    push("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
    print_list();
}
